package com.lebang.service.sys;

import com.lebang.component.RedisClient;
import com.lebang.domain.AppMainBanner;
import com.lebang.example.AppMainBannerExample;
import com.lebang.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
* 首页轮播
* @Author hwq
* @Date 2020-04-09
*/
@Service
public class AppMainBannerService extends BaseService<AppMainBanner, Integer, AppMainBannerExample>{
    @Autowired
    private RedisClient redisClient;
    private static final String REDIS_KEY = "APPMAINBANNER:SORT";
    private static final String KEY_MAX_COUNT = "AppMainBanner:KEY_MAX_COUNT";
    private static final String MEMBER_APPROUSEPLAN_COUNT = "AppMainBanner:MEMBER_APPROUSEPLAN_COUNT";

    public void initData() {

        AppMainBannerExample example = new AppMainBannerExample();
        List<AppMainBanner> list = this.selectByExample(example);
        redisClient.del(REDIS_KEY);
        list.forEach(s -> {
            redisClient.hset(REDIS_KEY , s.getCount().toString(), s.getSdkKey());
        });
        redisClient.set(KEY_MAX_COUNT,  String.valueOf(list.size()));
    }

    /**
     * 根据次数获取轮播
     *
     * @return
     */
    public String getKeyByCount(String memberId) {
        //取该计划的 轮播最大值
        Optional<String> max = Optional.ofNullable(redisClient.get(KEY_MAX_COUNT));
        Integer maxCount = max.map(Integer::parseInt).orElse(0);
        //取该用户轮播到几了 如果到最大了 就从0开始
        Long memberCount = redisClient.hincrby(MEMBER_APPROUSEPLAN_COUNT, memberId, 1L);
        if (memberCount >= maxCount) {
            redisClient.hset(MEMBER_APPROUSEPLAN_COUNT, memberId, "0");
        }
        //取本次轮播的key
        Optional<String> str = redisClient.Optionalhget(REDIS_KEY , String.valueOf(memberCount));
        return str.orElse("CSJ");
    }

    public boolean check(String s) {
        return redisClient.hexists(KEY_MAX_COUNT, s);
    }
}
